package com.regulareport.form.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.googlecode.aviator.AviatorEvaluator;
import com.regulareport.common.constant.ReportVerifyConstants;
import com.regulareport.common.core.domain.entity.*;
import com.regulareport.common.enums.TaskStatus;
import com.regulareport.common.enums.VerificationThreatLevel;
import com.regulareport.common.enums.VerificationType;
import com.regulareport.common.utils.DateUtils;
import com.regulareport.common.utils.SecurityUtils;
import com.regulareport.common.utils.StringUtils;
import com.regulareport.common.utils.parser.VerifyFormulaParser;
import com.regulareport.form.domain.ReportVerificationConfig;
import com.regulareport.form.domain.ReportVerificationResult;
import com.regulareport.form.domain.excel.ReportVerificationResultExcel;
import com.regulareport.form.mapper.*;
import com.regulareport.form.service.IReportVerificationResultService;
import com.regulareport.system.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 校验结果Service业务层处理
 * 
 * @author
 * @date 2025-10-08
 */
@Service
public class ReportVerificationResultServiceImpl implements IReportVerificationResultService
{
    private static final Logger log = LoggerFactory.getLogger(ReportVerificationResultServiceImpl.class);
    @Autowired
    private ReportVerificationResultMapper reportVerificationResultMapper;

    @Autowired
    private ReportVerificationConfigMapper reportVerificationConfigMapper;

    @Autowired
    private ReportFormsEditMapper reportFormsEditMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ReportTaskMapper reportTaskMapper;

    @Autowired
    private ReportIndexResultMapper reportIndexResultMapper;

    @Autowired
    private ReportCellDefinitionMapper reportCellDefinitionMapper;

    private final String numericPattern = "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$";

    private final String regex = "(?<![<=>!])=(?!=)";

    /**
     * 查询校验结果
     * 
     * @param reportFormId 校验结果主键
     * @return 校验结果
     */
    @Override
    public ReportVerificationResult selectReportVerificationResultByPkId(Long reportFormId, Long verifyConfigId)
    {
        return reportVerificationResultMapper.selectReportVerificationResultByPkId(reportFormId, verifyConfigId);
    }

    /**
     * 查询校验结果列表
     * 
     * @param reportVerificationResult 校验结果
     * @return 校验结果
     */
    @Override
    public List<ReportVerificationResult> selectReportVerificationResultList(ReportVerificationResult reportVerificationResult)
    {
        return reportVerificationResultMapper.selectReportVerificationResultList(reportVerificationResult);
    }

    /**
     * 新增校验结果
     * 
     * @param taskIds 校验结果
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map processReportVerificationResult(String taskIds)
    {
        Map resultVerifyMap = new HashMap();
        Map<String, List<ReportIndexResult>> verifyCellnMap = new HashMap<>();
        String[] taskIdArr = taskIds.split(",");
        List<ReportTask> reportTaskList = reportTaskMapper.selectReportTaskByTaskIds(taskIdArr);
        List<Long> reportIds = reportTaskList.stream()
                .map(ReportTask::getReportId)
                .distinct()
                .collect(Collectors.toList());
        List<Long> deptIds = reportTaskList.stream()
                .map(ReportTask::getDeptId)
                .distinct()
                .collect(Collectors.toList());
        try {
            List<ReportFormsEdit> formsEditList = reportFormsEditMapper.selectReportFormsEditByPkIds(reportIds);
            List<SysDept> sysDeptList = sysDeptMapper.selectSysDeptByPkIds(deptIds);
            for(ReportTask task : reportTaskList){
                List<ReportFormsEdit> subFormsEditList = formsEditList.stream().filter(f->f.getPkId().equals(task.getReportId())).collect(Collectors.toList());
                List<SysDept> subSysDeptList = sysDeptList.stream().filter(f->f.getDeptId().equals(task.getDeptId())).collect(Collectors.toList());
                ReportFormsEdit formsEdit = new ReportFormsEdit();
                SysDept sysDept = new SysDept();
                if(!CollectionUtils.isEmpty(subFormsEditList)){
                    formsEdit = subFormsEditList.get(0);
                }
                if(!CollectionUtils.isEmpty(subSysDeptList)){
                    sysDept = subSysDeptList.get(0);
                }
                Map reportFormResultVerifyMap = new HashMap();
                List<ReportVerificationResult> totalVerificationResultList = new ArrayList<>();
                List<ReportVerificationResult> failVerifyResultList = new ArrayList<>();
                int internalSuccessInt = 0 ;
                int externalSuccessInt = 0 ;
                int suggestiveSuccessInt = 0 ;
                int internalFailInt = 0 ;
                int externalFailInt = 0 ;
                int suggestiveFailInt = 0 ;
                int threatLevelFailInt = 0 ;  //当强制性校验时，失败计数

                ReportVerificationConfig verifyConfigParams = new ReportVerificationConfig();
                verifyConfigParams.setReportFormId(task.getReportId());
                verifyConfigParams.setReportFormNo(formsEdit.getReportFormNo());
                List<ReportVerificationConfig> reportVerificationConfigList = reportVerificationConfigMapper.selectVerificationConfigListByReportFormNoEdition(String.valueOf(task.getReportId()),
                        formsEdit.getReportFormNo());
                //遍历每一条 校验配置
                for(ReportVerificationConfig config : reportVerificationConfigList){
                    boolean verifyResult = true; //校验结果 true/false
                    ReportVerificationResult verificationResult = new ReportVerificationResult();//校验结果表
                    verificationResult.setIndexNo(config.getIndexNo());
                    verificationResult.setIndexName(config.getIndexName());
                    verificationResult.setVerificationConfigID(config.getPkId());
                    verificationResult.setVerificationFormula(config.getVerificationFormula());
                    verificationResult.setVerificationDescribe(config.getVerificationDescribe());
                    verificationResult.setReportFormNo(config.getReportFormNo());
                    verificationResult.setReportFormName(config.getReportFormName());
                    verificationResult.setDeptId(SecurityUtils.getLoginUser().getDeptId());
                    verificationResult.setDeptNum(sysDept.getDeptNum());
                    verificationResult.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                    verificationResult.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
                    verificationResult.setTolerance("0.015");
                    verificationResult.setReportFormId(config.getReportFormId());
                    verificationResult.setVerificationType(config.getVerificationType());
                    String ymd = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.dateTime(DateUtils.YYYYMMDD, task.getDataDate()));
                    verificationResult.setAnalysisDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD, ymd));

                    ReportIndexResult verifyReportIndexRes = new ReportIndexResult();
                    String verificationFormula = config.getVerificationFormula();
                    //已查询到报表的指标定义信息
                    List<ReportIndexResult> existDefineList = verifyCellnMap.get(String.valueOf(task.getReportId()));

                    String[] levels = config.getOrgScope().split(",");
                    //判断该报表id的指标结果集是否已查询存在，不存在时查询并赋值到verifyCellnMap
                    if(CollectionUtils.isEmpty(existDefineList)) {
                        Long verifyReportFormId = config.getReportFormId();
                        verifyReportIndexRes.setReportFormNo(config.getReportFormNo());
                        verifyReportIndexRes.setIndexNo(config.getIndexNo());
                        if (verifyReportFormId == null) {
                            verifyReportIndexRes.setReportFormID(task.getReportId());
                        } else {
                            verifyReportIndexRes.setReportFormID(verifyReportFormId);
                        }
                        //当前校验的报表指标列表
                        List<ReportIndexResult> verifyReportCellList = reportIndexResultMapper.selectReportIndexResultListByDeptLevel(levels, config.getReportFormNo());
                        if(CollectionUtils.isEmpty(verifyReportCellList)) {
                            log.error("当前校验的报表指标列表结果为空 ========= reportFormId:{} ---------------indexNo:{}", config.getReportFormId(), config.getIndexNo());
                            verifyResult = false;
                            if(VerificationType.INTERNAL.getCode().equals(config.getVerificationType())) {
                                internalFailInt++;
                            } else if(VerificationType.EXTERNAL.getCode().equals(config.getVerificationType())){
                                externalFailInt++;
                            } else{
                                suggestiveFailInt++;
                            }
                            //当强制性校验时，计数
                            if(config.getThreatLevel().equals(VerificationThreatLevel.WARN.getCode())) {
                                threatLevelFailInt++;
                            }
                            verificationResult.setVerificationResult(verifyResult);
                            verificationResult.setRemark("lackIndexResultValue");
                            failVerifyResultList.add(verificationResult);
                            totalVerificationResultList.add(verificationResult);
                            continue;
                        }
                        verifyCellnMap.put(String.valueOf(verifyReportIndexRes.getReportFormID()), verifyReportCellList);
                    }

                    //表间校验 或 提示校验   查询报表定义列表
                    if (VerificationType.EXTERNAL.getCode().equals(config.getVerificationType()) || VerificationType.SUGGESTIVE.getCode().equals(config.getVerificationType())) {
//                        ReportIndexResult externalVerifyReportIndexRes = new ReportIndexResult();
                        Long subReportFromId = config.getReportFormIdSon();
                        String subReportFromNo = config.getReportFormNoSon();
                        ReportFormsEdit subReportForm;
                        //判断是否涉及表间校验，提示校验不一定涉及表间。涉及表间则需要查询另一表的指标结果集
                        if(StringUtils.isNotEmpty(subReportFromNo)){
                            if (subReportFromId == null) {
                                //根据版本号获取到该报表编号最新的报表ID
                                subReportForm = reportFormsEditMapper.selectReportFormsEditLatest(subReportFromNo);
                                if (subReportForm != null && !subReportForm.equals("")) {
                                    subReportFromId = subReportForm.getPkId();
                                }
                            }

                            if (subReportFromId != null) {
                                List<ReportIndexResult> existSubDefineList = verifyCellnMap.get(String.valueOf(subReportFromId));
                                if (CollectionUtils.isEmpty(existSubDefineList)) {
//                                    externalVerifyReportIndexRes.setReportFormID(subReportFromId);
                                    //表间校验查询外表所有指标定义列表
                                    List<ReportIndexResult>  externalSuggestiveReportCellDefList = reportIndexResultMapper.selectReportIndexResultListByDeptLevel(levels, subReportFromNo);
                                    if(!CollectionUtils.isEmpty(externalSuggestiveReportCellDefList)) {
                                        verifyCellnMap.put(String.valueOf(subReportFromId), externalSuggestiveReportCellDefList);
                                    } else {
                                        log.info("表间校验查询外表所有指标定义列表为空========机构层级：{}--------报表编号：{}", levels, config.getReportFormNo());
                                    }
                                }
                            } else {
                                System.out.println("表间校验或提示性校验, 表间的报表ID未查询到 ======== 报表编号为：" + subReportFromNo);
                                verifyResult = false;
                                verificationResult.setVerificationResult(verifyResult);
                                if(VerificationType.EXTERNAL.getCode().equals(config.getVerificationType())){
                                    externalFailInt++;
                                } else {
                                    suggestiveFailInt++;
                                }
                                //当强制性校验时，计数
                                if(config.getThreatLevel().equals(VerificationThreatLevel.WARN.getCode())) {
                                    threatLevelFailInt++;
                                }
                                failVerifyResultList.add(verificationResult);
                                totalVerificationResultList.add(verificationResult);
                                continue;
                            }
                        }
                    }
                    //组装查询到的指标结果数据集
                    List<ReportIndexResult> resultReportCellDefList = new ArrayList<>();
                    verifyCellnMap.forEach((key, value) -> {
                        resultReportCellDefList.addAll(value);
                     });

                   //解析公式中的指标编号为指标编号数组
                   List<String> subFormalStr = VerifyFormulaParser.parseFormula(verificationFormula, ReportVerifyConstants.OPERATOR_ARR);
                   List<String> lackFormaleList = new ArrayList<>();
                   //灰格子
                   List<String> greyFormaleList = new ArrayList<>();
                   Map<String, Object> indexNoValueMap =  new HashMap();
                   for(String elementIndex : subFormalStr){
                       // 匹配整数、小数、科学计数法元素不用查询该期指标值
                       if(!Pattern.matches(numericPattern, elementIndex.trim())) {
                           List<ReportIndexResult> reportCellDefMatchList = resultReportCellDefList.stream().filter(r -> elementIndex.equals(r.getIndexNo()) && ymd.equals(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, r.getDataDate()))).collect(Collectors.toList());
                           if (!CollectionUtils.isEmpty(reportCellDefMatchList)) {
                               //匹配成功的指标结果集，只取第一个结果
                               if(reportCellDefMatchList.get(0).getIndexSubmittedValue() != null) {
                                   //AviatorEvaluator.execute不识别公式字符串变量名有小数点的情况，所以需要处理为下划线
                                   indexNoValueMap.put(elementIndex.replaceAll("\\.", "_"), reportCellDefMatchList.get(0).getIndexSubmittedValue());
                               } else {
                                   lackFormaleList.add(elementIndex);
                                   log.error("指标结果集某个指标：{} 结果为空====================报表ID：{}-", elementIndex, task.getReportId());
                               }
//                           verificationResult.setAnalysisDate(reportCellDefMatchList.get(0).getDataDate());
                           } else {
                               ReportCellDefinition cellDef = reportCellDefinitionMapper.selectReportCellDefinitionByIndexNo(String.valueOf(task.getReportId()), elementIndex);
                               if(cellDef != null ) {
                                   //未查询到的指标编号
                                   lackFormaleList.add(elementIndex);
                               } else {
                                   //灰色单元格值默认为0
                                   indexNoValueMap.put(elementIndex.replaceAll("\\.", "_"), new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP));
                                   //校验公式可能涉及灰色单元格
                                   greyFormaleList.add(elementIndex);
                               }
                           }
                       } else {
                           //当公式元素为小数时，将小数值放在值Map中，因为规则校验时需要替换公式中的小数点
                           if(elementIndex != null && elementIndex.indexOf(".") > -1) {
//                               String tests111 =  verificationFormula.replaceAll("([A-Za-z])\\.|\\.([A-Za-z])|\\.(?!\\d)", "$1_$2_");
                               verificationFormula = verificationFormula.replace(elementIndex, elementIndex.replace(".","@"));
                           }
                       }
                   }
                   //当指标编号全部匹配
                   if(CollectionUtils.isEmpty(lackFormaleList)){
                      //判断校验公式只包含一个 等号"=",不包含其他涉及等号的运算符情况，替换等号为双等。判定，公式不可能有一个等号之后还包含其他有等号的运算符
                      String processFormula = verificationFormula.replaceAll(regex, "==");
                      //先处理公式中的小数点
                      String stripDivisorZeroFormula = extractDivisionFormulas(processFormula.replaceAll("\\.","_"), indexNoValueMap);
                      //当公式中的元素包含小数点时，校验方法AviatorEvaluator.execute不识别，所以处理所有小数点.为下划线，处理结果统一为布尔类型
                       try {
                           verifyResult =  (Boolean) AviatorEvaluator.execute(stripDivisorZeroFormula.replaceAll("@", "."), indexNoValueMap);
                       } catch (Exception e) {
                           log.error("错误公式：==================processFormula：{}---------------处理后的公式：{}++++++++++++++++++++++值：{}", processFormula, processFormula.replaceAll("\\.","_").replaceAll("@", "."), indexNoValueMap.toString());
                           throw new RuntimeException(e);
                       }
                       if(!verifyResult){
                          //当校验结果失败时，对校验公式进行依据逻辑判断符的切割，当切割为2部分时，进行左右公式结果值计算。否则不做处理（涉及计算某个区间的情况）。
                          List<String> faileFormalStr = VerifyFormulaParser.parseFormula(processFormula, ReportVerifyConstants.OPERATOR_COMPARE_ARR);
                          if(faileFormalStr != null && faileFormalStr.size() == 2){
                             //左边的公式
                             BigDecimal leftVerifyResult = processFormalEleList(faileFormalStr.get(0),  indexNoValueMap);
                             //右边的公式
                             BigDecimal rightVerifyResult = processFormalEleList(faileFormalStr.get(1),  indexNoValueMap);
                             BigDecimal difSubtract = null;
                             if(leftVerifyResult != null && rightVerifyResult != null) {
                                 difSubtract = leftVerifyResult.setScale(6, BigDecimal.ROUND_HALF_UP).subtract(rightVerifyResult.setScale(6, BigDecimal.ROUND_HALF_UP));
                                 BigDecimal tolerance = new BigDecimal(verificationResult.getTolerance()).setScale(6, BigDecimal.ROUND_HALF_UP);
                                 //当左右差值的绝对值大于0.015时， 校验结果为false,负责在设置的容差范围之内，为正数
                                 verifyResult = difSubtract.abs().compareTo(tolerance.abs()) <= 0 ?  true : false;
                             } else {
                                 log.info("左右值有为null的情况=====reportFormID：{}--------- leftValue:{},-----rightValue:{}",  config.getReportFormId(), leftVerifyResult, rightVerifyResult);
                             }
//                             log.info("左右值的情况=====reportFormID：{}----formula:{} ---左右差值--difSubtract:{}", config.getReportFormId(), verificationFormula, difSubtract);
                             verificationResult.setLeftValue(leftVerifyResult);
                             verificationResult.setRightValue(rightVerifyResult);
                             verificationResult.setDifferenceValue(difSubtract);
                          }
                          verificationResult.setVerificationResult(verifyResult);
                          if(!verifyResult) {
                              failVerifyResultList.add(verificationResult);
                              if (VerificationType.INTERNAL.getCode().equals(config.getVerificationType())) {
                                  internalFailInt++;
                              } else if (VerificationType.EXTERNAL.getCode().equals(config.getVerificationType())) {
                                  externalFailInt++;
                              } else {
                                  suggestiveFailInt++;
                              }
                              //当强制性校验时，计数
                              if (config.getThreatLevel().equals(VerificationThreatLevel.WARN.getCode())) {
                                  threatLevelFailInt++;
                              }
                          } else {
                              if(VerificationType.INTERNAL.getCode().equals(config.getVerificationType())) {
                                  internalSuccessInt++;
                              } else if(VerificationType.EXTERNAL.getCode().equals(config.getVerificationType())){
                                  externalSuccessInt++;
                              } else{
                                  suggestiveSuccessInt++;
                              }
                          }
                      } else {
                          List<String> successFormalStr = VerifyFormulaParser.parseFormula(processFormula, ReportVerifyConstants.OPERATOR_COMPARE_ARR);
                          if(successFormalStr != null && successFormalStr.size() == 2){
                              //左边的公式
                              BigDecimal leftVerifyResult = processFormalEleList(successFormalStr.get(0),  indexNoValueMap);
                              //右边的公式
                              BigDecimal rightVerifyResult = processFormalEleList(successFormalStr.get(1),  indexNoValueMap);
                              BigDecimal difSubtract = null;
                              if(leftVerifyResult != null && rightVerifyResult != null) {
                                  difSubtract = leftVerifyResult.subtract(rightVerifyResult);
                              } else {
                                  log.info("校验结果为true时：左右值有为null的情况=====reportFormID：{}------- leftValue:{},-----rightValue:{}",  config.getReportFormId(), leftVerifyResult, rightVerifyResult);
                              }
                              log.info("校验结果为true时：左右值的情况=====reportFormID：{}-------difSubtract:{}", config.getReportFormId(), difSubtract);
                              verificationResult.setLeftValue(leftVerifyResult);
                              verificationResult.setRightValue(rightVerifyResult);
                              verificationResult.setDifferenceValue(difSubtract);
                          }
                          verificationResult.setVerificationResult(verifyResult);
                          if(VerificationType.INTERNAL.getCode().equals(config.getVerificationType())) {
                              internalSuccessInt++;
                          } else if(VerificationType.EXTERNAL.getCode().equals(config.getVerificationType())){
                              externalSuccessInt++;
                          } else{
                              suggestiveSuccessInt++;
                          }
                      }
                   } else {
                       StringBuilder lackStr = new StringBuilder();
                       for(String lackEle : lackFormaleList){
                           if (lackStr.length() > 0) {
                               lackStr.append(" @ ").append(lackEle);
                           } else {
                               lackStr.append(lackEle);
                           }
                       }
                       verificationResult.setVerificationResult(false);
                       verificationResult.setRemark(lackStr.toString());
                       failVerifyResultList.add(verificationResult);
                       if(VerificationType.INTERNAL.getCode().equals(config.getVerificationType())) {
                           internalFailInt++;
                       } else if(VerificationType.EXTERNAL.getCode().equals(config.getVerificationType())){
                           externalFailInt++;
                       } else{
                           suggestiveFailInt++;
                       }
                       //当强制性校验时，计数
                       if(config.getThreatLevel().equals(VerificationThreatLevel.WARN.getCode())) {
                           threatLevelFailInt++;
                       }
                   }
                   if(verificationResult.getAnalysisDate() == null){
                       verificationResult.setAnalysisDate(DateUtils.getNowDate());
                   }

                   totalVerificationResultList.add(verificationResult);
                }

                reportFormResultVerifyMap.put("failVerifyList", failVerifyResultList);
//                reportFormResultVerifyMap.put("totalVerifyList", totalVerificationResultList);
                reportFormResultVerifyMap.put("internalFailNum", internalFailInt);
                reportFormResultVerifyMap.put("externalFailNum", externalFailInt);
                reportFormResultVerifyMap.put("suggestiveFailNum", suggestiveFailInt);
                reportFormResultVerifyMap.put("internalSucNum", internalSuccessInt);
                reportFormResultVerifyMap.put("externalSucNum", externalSuccessInt);
                reportFormResultVerifyMap.put("suggestiveSucNum", suggestiveSuccessInt);

                resultVerifyMap.put(formsEdit.getReportFormNo(), reportFormResultVerifyMap);
                int successInt = 0;
                if(!CollectionUtils.isEmpty(totalVerificationResultList)){
                     successInt = reportVerificationResultMapper.batchInsertReportVerificationResult(totalVerificationResultList);
                }
                log.info("插入成功========={}条------reportFormNO:{}", successInt, formsEdit.getReportFormNo());
                //internalFailInt、externalFailInt、suggestiveFailInt任一都不可能为负数所以判断三者之和是否为0、校验非强制性时，不卡校验失败数
                if(((internalFailInt + externalFailInt + suggestiveFailInt) == 0 || threatLevelFailInt == 0) && TaskStatus.BL.getCode().equals(task.getTaskStatus())) {
                    task.setTaskStatus("5");
                    task.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
                    log.info("待更新fillingRep值============------{}", task.toString());
                    //当task的状态为IMPORT，导入时，需要变更task的状态为VERIFY  数据校验
                    int resultNum = reportTaskMapper.updateTaskStatusVerify(task);
                    log.info("更新成功报表任务状态========{}条------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return resultVerifyMap;
    }

    /**
     * 修改校验结果
     * 
     * @param reportVerificationResult 校验结果
     * @return 结果
     */
    @Override
    public int updateReportVerificationResult(ReportVerificationResult reportVerificationResult)
    {
        reportVerificationResult.setUpdateTime(DateUtils.getNowDate());
        return reportVerificationResultMapper.updateReportVerificationResult(reportVerificationResult);
    }

    /**
     * 批量删除校验结果
     * 
     * @param pkIds 需要删除的校验结果主键
     * @return 结果
     */
    @Override
    public int deleteReportVerificationResultByPkIds(Long[] pkIds)
    {
        return reportVerificationResultMapper.deleteReportVerificationResultByPkIds(pkIds);
    }

    /**
     * 删除校验结果信息
     * 
     * @param pkId 校验结果主键
     * @return 结果
     */
    @Override
    public int deleteReportVerificationResultByPkId(Long pkId)
    {
        return reportVerificationResultMapper.deleteReportVerificationResultByPkId(pkId);
    }

    private BigDecimal processFormalEleList(String formalStr, Map<String, Object> indexValueMap) {
        List<String> SubForStrList = VerifyFormulaParser.parseFormula(formalStr, ReportVerifyConstants.OPERATOR_ARR);
        BigDecimal lefRigValue = new BigDecimal("0.00").setScale(6, BigDecimal.ROUND_HALF_UP);
        Map indexNoValueMap = new HashMap();
        if (CollectionUtils.isEmpty(SubForStrList)) {
            return null;
        }
        try {
            for (String subFormalEle : SubForStrList) {
                //匹配是否为小数，整数，科学计数符
                if(!Pattern.matches(numericPattern, subFormalEle.trim())) {
                    if(indexValueMap.get(subFormalEle.replaceAll("\\.", "_")) != null ) {
                        indexNoValueMap.put(subFormalEle.replaceAll("\\.", "_"), new BigDecimal(String.valueOf(indexValueMap.get(subFormalEle.replaceAll("\\.", "_")))));
                    } else {
                        log.error("左边或右边的计算出错===============指标编号：{}---------原值组：{}----", subFormalEle, indexValueMap.toString());
                        lefRigValue = null;
                        break;
                    }
                }
            }
            if(lefRigValue != null) {
                //处理formula中的子除法表达式
                String stripDivisorSubFormula = extractDivisionFormulas(formalStr.replaceAll("\\.", "_"), indexNoValueMap);
                lefRigValue = new BigDecimal(String.valueOf(AviatorEvaluator.execute(stripDivisorSubFormula, indexNoValueMap))).setScale(6, BigDecimal.ROUND_HALF_UP);
            }
        } catch (Exception e) {
            log.error("左边或右边的计算出错==========公式：{}， 值：{},  原值：{} ", formalStr, indexNoValueMap.toString(), indexValueMap.toString());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return lefRigValue;
    }

    /**
     * 提取所有除法子公式并处理
     * @param formula 输入的公式字符串
     * @return 除法子公式列表
     */
    private String extractDivisionFormulas(String formula, Map indexNoValueMap) {
        List<String> divisionFormulas = new ArrayList<>();
        if (formula == null || formula.trim().isEmpty()) {
            return formula;
        }
        // 正则表达式匹配除法运算：数字/变量名 运算符 数字/变量名
        String divisionRegex = "(?<![\\w.])[a-zA-Z_]\\w*\\s*/\\s*[a-zA-Z_]\\w*(?![\\w.])";
        Pattern pattern = Pattern.compile(divisionRegex);
        Matcher matcher = pattern.matcher(formula);

        while (matcher.find()) {
            String divisionFormula = matcher.group().trim();
            divisionFormulas.add(divisionFormula);
            System.out.println("找到除法子公式: " + divisionFormula);
        }

        Map<String, String> divisionZero = new HashMap<>();
        if(!CollectionUtils.isEmpty(divisionFormulas)){
            for(String str : divisionFormulas){
                String[] divisionArr = str.split("/");
                if(divisionArr != null && divisionArr.length == 2 ){
                    String divisor = divisionArr[1];
                    if(!(indexNoValueMap.get(divisor) != null && !"".equals(indexNoValueMap.get(divisor)) && new BigDecimal(String.valueOf(indexNoValueMap.get(divisor))).compareTo(BigDecimal.ZERO) != 0)) {
                        divisionZero.put(str, "0");
                    }
                }
            }
        }
        if(!CollectionUtils.isEmpty(divisionZero)){
            Iterator<Map.Entry<String, String>> iterator = divisionZero.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                String divisionSubFormal = entry.getKey();
                formula = formula.replace(divisionSubFormal, entry.getValue());
                System.out.println("----subFormalDivision: " + entry.getKey() +"==================formal :  " +formula);
            }
        }
        return formula;
    }

    /**
     * 校验结果的批量导出
     * @param taskIds
     * @return
     */
    @Override
    public Map<String, List<ReportVerificationResultExcel>> selectReportVerificationResultMap(String taskIds) throws Exception {
        if(StringUtils.isEmpty(taskIds)){
             throw new Exception("未选中任何待导出任务");
         }
        String[] taskIdArr = taskIds.split(",");
        List<ReportTask> reportTaskList = reportTaskMapper.selectReportTaskByTaskIds(taskIdArr);
        if(CollectionUtils.isEmpty(reportTaskList)){
            throw new Exception("未查询到任何待导出任务");
        }
        Map<String, List<ReportVerificationResultExcel>> reportVerificationResultMap = new HashMap<>();
        List<Long> reportIds = reportTaskList.stream().map(ReportTask::getReportId).collect(Collectors.toList());
        List<ReportFormsEdit> editList = reportFormsEditMapper.selectReportFormsEditByPkIds(reportIds);
        //避免当某个报表无数据时，不展示改报表的校验结果sheet
        for(ReportFormsEdit edit : editList){
            reportVerificationResultMap.put(edit.getReportFormNo(), null);
        }
        for(ReportTask rt : reportTaskList){
            ReportVerificationResult verificationResult = new ReportVerificationResult();
            verificationResult.setReportFormId(rt.getReportId());
            Date tempDate = DateUtils.dateTime(DateUtils.YYYYMMDD, rt.getDataDate());
            verificationResult.setAnalysisDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, tempDate)));
            verificationResult.setDeptId(rt.getDeptId());
            List<ReportVerificationResultExcel>  verificationResults = reportVerificationResultMapper.selectExportReportVerificationResultList(verificationResult);
            if(!CollectionUtils.isEmpty(verificationResults) && reportVerificationResultMap.containsKey(verificationResults.get(0).getReportFormNo())) {
                reportVerificationResultMap.put(verificationResults.get(0).getReportFormNo(), verificationResults);
            }
        }

        return reportVerificationResultMap;
    }
}
